package com.gorkr.labuladong.data_struct;

/**
 * @author gorkr
 * @date 2022/06/01 21:08
 **/
public class M222CountCompleteTreeNodes {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int countNodes(TreeNode root) {

        if (root == null) {
            return 0;
        }

        TreeNode l = root, r = root;
        int hl = 0, hr = 0;
        while (l != null) {
            hl++;
            l = l.left;
        }
        while (r != null) {
            hr++;
            r = r.right;
        }
        // root 为根的子树为满二叉树
        // 当root==null 时该语句也通过
        if (hl == hr) {
            return (int) Math.pow(2, hr) - 1;
        }
        return 1 + countNodes(root.left) + countNodes(root.right);

    }

}
    